package com.system

import com.common.JsoupUtils
import grails.converters.JSON
import grails.web.controllers.ControllerMethod
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.Payload
import org.springframework.messaging.handler.annotation.SendTo
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.messaging.simp.annotation.SendToUser
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.web.context.request.RequestContextHolder

class MessageController {

    SimpMessagingTemplate brokerMessagingTemplate
//    def messageService

    def index() {
        String sid = getUid()
        [sid:sid]
    }

    @ControllerMethod
    @MessageMapping("/hello")
    @SendTo("/topic/hello")
//    @Payload(required=false)
    protected String hello(Map<String,Object> message) {
        def map = [:]
        def msg = JsoupUtils.cleanXss(message.msg)?:'<br/>'
        if(msg.contains("<img")){
            msg += "&nbsp;"
        }
        map.msg = msg
        map.sid = message.sid
        return map as JSON
    }

    def user = {

    }

    public String getUid() {
        return RequestContextHolder?.currentRequestAttributes()?.sessionId.toString()
    }

    def notice = {

    }


    def appoint = {
        String sid = getUid()
        [sid:sid]
    }

    @MessageMapping("/msg")
//    @SendToUser("/queue/msg")
    protected void msg(Map<String,Object> message) {
//        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()
//        println "${userDetails.getUsername()}"
        println message
        brokerMessagingTemplate.convertAndSendToUser message.username, '/queue/msg', "hello"
//        def map = [:]
//        def msg = JsoupUtils.cleanXss(message.msg)?:'<br/>'
//        if(msg.contains("<img")){
//            msg += "&nbsp;"
//        }
//        map.msg = msg
//        map.sid = message.sid
//        return message.msg
    }
}
